﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;

namespace QualityStorm {
    public partial class FrmLogin : Form {
        public FrmLogin() {
            InitializeComponent();
        }

        private void cboServers_SelectedIndexChanged(object sender, EventArgs e) {
            if (cboServers.SelectedItem.ToString() == "<Add New Server>") {
                FrmServerSetup frm = new FrmServerSetup();
                frm.ShowDialog();
            }

        }

        private void btnOK_Click(object sender, EventArgs e) {
            try {
                foreach (TcpChannel tcp in ChannelServices.RegisteredChannels) {
                    ChannelServices.UnregisterChannel(tcp);
                }
                TcpChannel chan = new TcpChannel();
                ChannelServices.RegisterChannel(chan);
                // Create an instance of the remote object
                QualityStormCommon.QualityStormService service =
                 (QualityStormCommon.QualityStormService)Activator.GetObject(
                  typeof(QualityStormCommon.QualityStormService), "tcp://" + ApplicationSettings.Server + ":" + ApplicationSettings.ObjectServerPort + "/QualityStormService");

                if (!service.Login(txtLogin.Text, txtPassword.Text)) {
                    MessageBox.Show("Login failed for this user!");

                } else {
                    ConnectionContext context = new ConnectionContext();
                    context.Service = service;
                    context.Login = txtLogin.Text;
                    context.ServerName = ApplicationSettings.Server;
                    GlobalObjects.Connections.Add(context);
                    FrmMain frm = new FrmMain();
                    Close();

                }
            } catch {
                MessageBox.Show("Error when trying to connect to the server!", "Attention!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }
    }
}
